package cate.game.server.schedule;

import cate.game.GameBody;
import cate.game.ManyGame;
import cate.game.server.controller.PlatformSupportController;
import cp.game.framework.ApiCaller;
import cp.game.framework.ConfigFromConsole;
import cp.platform.common.GsActivationReq;
import cp.platform.common.GsActivationResp;
import cp.solution.define.Project;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Collection;

@Slf4j
@Configuration
@EnableScheduling
public class PlatformSchedule {

    private final ManyGame games;
    private final ApiCaller apiCaller;
    private final ConfigFromConsole cfc;

    public PlatformSchedule(ManyGame games, ApiCaller apiCaller, ConfigFromConsole cfc) {
        this.games = games;
        this.apiCaller = apiCaller;
        this.cfc = cfc;
    }

    @Scheduled(fixedDelay = 5000, initialDelay = 3000)
    public void active() {
        try {
            Collection<GameBody> all = this.games.getAllIncludeNotOpen();
            if(all == null || all.isEmpty()) {
                return;
            }

            GsActivationReq cmd = new GsActivationReq();
            cmd.setProjectId(Project.C2.id);
            cmd.setEnvCode(cfc.progressBootstrap.getEnvCode());

            for(GameBody game : all) {
                String gsName = game.config.gs.getName();
                String groupCode = game.config.gs.getGroupCode();
                long srvTime = game.time.now();
                String gsId = ""+game.config.srvId;
                cmd.addGs(gsId, gsName, groupCode, true, srvTime);
            }

            String host = cfc.progressBootstrap.getServer().toLocalHost();
            // 不要使用以下方法获取webPort，因为当自己本机启动服务器时，是直接读取application.yml中的server.port
            //int webPort = cfc.progressBootstrap.getProcess().getWebPort();
            int webPort = games.config.webPort;
            cmd.setHost(host);
            cmd.setHttpPort(webPort);
            cmd.setSystemTime(System.currentTimeMillis());
            cmd.getApiConf().setResSendPath("GameSrv尚未编写相关代码去支持/res/send");
            cmd.getApiConf().setMsgPushPath(PlatformSupportController.getPath(PlatformSupportController.PATH_MSG_PUSH));
            GsActivationResp resp = apiCaller.pc().platform.foundation.activeGameServer(cmd);
            if(!resp.ok()) {
                log.warn("向platform平台服务激活失败 因为：{}", resp.em);
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
